<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            list-style: none;
        }
        #box{
            width: 800px;
            border: 1px solid #ccc;
            margin: 100px auto;
            padding: 20px;
        }
        #my_textarea{
            width: 80%;
            height: 120px;
            padding: 10px;

        }
        #ul{
            margin: 0 75px;

        }
        #ul li{
            border-bottom: 1px dashed #ccc;
            color: red;
            line-height: 44px;
        }
        #ul li a{
            float: right;
        }
    </style>
</head>
<body>
    <div id="box">
        <div class="box-top">
            <label for="my_textarea">发表评论：</label>
            <textarea name="my_textarea" id="my_textarea" cols="30" rows="10"></textarea>
            <button id="btn">发表</button>
        </div>
        <div class="box-bottom">
            <ul id="ul">
                <!-- <li>今天天气很好<a href="#">删除</a></li> -->
            </ul>
        </div>
    </div>

    <script>
        window.addEventListener("load",function(){
            $('btn').addEventListener("click",function(){
                //获取输入框中的内容
                let content = $('my_textarea').value;
                console.log(content);

                //判断内容是否为空
                if(content.trim().length===0){//content.trim()去掉内容中的空格
                    alert("请输入评论内容");
                    return;
                }
                //创建li标签放入ul
                let li = document.createElement('li');
                li.innerHTML = `${content}<a href="#">删除</a>`;
                $('ul').insertBefore(li,$('ul').children[0]);

                //清除输入框中的内容
                $('my_textarea').value="";

                //删除评论
                let as = $('ul').getElementsByTagName('a');//获得所有ul中的a标签
                for(let i = 0; i<as.length;i++){
                    let sa = as[i];
                    sa.addEventListener('click',function(){
                        this.parentElement.remove();
                    });
                }

            });
        });
        function $(id){
            return typeof id === "string"?document.getElementById(id) : null;
        }
    </script>
</body>
</html>